package com.jijuxie.message.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jijuxie.common.core.R;
import com.jijuxie.message.domain.ChatMessage;
import com.jijuxie.message.service.IChatMessageService;
import com.jijuxie.message.vo.ChatMessageVO;
import cn.dev33.satoken.stp.StpUtil;
import com.jijuxie.common.annotation.RateLimiter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@RestController
@RequestMapping("/chat")
public class ChatMessageController {

    private static final Logger log = LoggerFactory.getLogger(ChatMessageController.class);

    @Autowired
    private IChatMessageService chatMessageService;

    /**
     * 获取聊天列表
     */
    @GetMapping("/list")
    @RateLimiter(count = 10, time = 60)  // 限流: 每60秒允许10次请求
    public R<Page<ChatMessageVO>> getMessageList(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "20") Integer pageSize) {
        Long userId = StpUtil.getLoginIdAsLong();
        try {
            return R.ok(chatMessageService.getMessageList(userId, pageNum, pageSize));
        } catch (Exception e) {
            log.error("获取聊天列表失败: userId={}, error={}", userId, e.getMessage(), e);
            return R.fail("系统繁忙，请稍后重试");
        }
    }

    /**
     * 获取聊天记录
     */
    @GetMapping("/history/{targetUserId}")
    public R<Page<ChatMessage>> getChatHistory(
            @PathVariable Long targetUserId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "20") Integer pageSize) {
        Long userId = StpUtil.getLoginIdAsLong();
        return R.ok(chatMessageService.getChatHistory(userId, targetUserId, pageNum, pageSize));
    }

    /**
     * 发送消息
     */
    @PostMapping("/send")
    public R<Void> sendMessage(@RequestBody ChatMessage message) {
        Long userId = StpUtil.getLoginIdAsLong();
        message.setFromUserId(userId);
        chatMessageService.sendMessage(message);
        return R.ok();
    }

    /**
     * 标记已读
     */
    @PutMapping("/read/{targetUserId}")
    public R<Void> markRead(@PathVariable Long targetUserId) {
        Long userId = StpUtil.getLoginIdAsLong();
        chatMessageService.markRead(targetUserId, userId);
        return R.ok();
    }
}
